#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <unistd.h>
#include "student.h"

int main(int argc, char const *argv[]) {
    struct msgstru msgs;
    struct student stu;
    char str[256];
    int ret_value;
    int msqid;

    //检查消息队列是否存在
    msqid = msgget(MSGKEY, IPC_EXCL); //(键名,权限)
    if (msqid < 0) {
        //创建消息队列
        msqid = msgget(MSGKEY, IPC_CREAT | 0666);
        if (msqid < 0) {
            printf("failed to create msq | errno=%d [%s]\n", errno, strerror(errno));
            exit(-1);
        }
    }

    //父进程
    while (1) {
        stu.id = 123456;
        stu.age = 12;
        printf("input message to be sent:\n");
        scanf("%s", stu.name);

        msgs.msgtype = MSGTYPE;
        memcpy(&msgs.stu, &stu, sizeof(stu));

        //发送消息队列(sizeof消息的长度，而不是整个结构体的长度)
        ret_value = msgsnd(msqid, &msgs, sizeof(msgs.stu), IPC_NOWAIT);
        if (ret_value < 0) {
            printf("msgsnd() write msg failed,errno=%d[%s]\n", errno, strerror(errno));
            exit(-1);
        }
    }

    printf("fork error\n");
    //删除消息队列
    msgctl(msqid, IPC_RMID, 0);
    exit(1);

    return 0;
}